<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <h3>{{ isEdit ? '编辑处方' : '新增处方' }}</h3>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        label-position="right"
        status-icon
      >
        <el-divider content-position="left">基本信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="处方编号" prop="prescriptionId">
              <el-input 
                v-model="form.prescriptionId" 
                placeholder="系统自动生成" 
                disabled
                v-if="isEdit"
              />
              <el-input 
                v-else
                v-model="form.prescriptionId" 
                placeholder="系统自动生成" 
                disabled
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="处方状态" prop="status">
              <el-select 
                v-model="form.status" 
                placeholder="请选择状态"
                style="width: 100%"
                :disabled="isEdit"
              >
                <el-option label="待审核" value="待审核" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">患者信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="患者" prop="patientId">
              <el-select 
                v-model="form.patientId" 
                filterable 
                remote 
                reserve-keyword
                placeholder="请输入患者姓名或ID搜索" 
                :remote-method="searchPatients"
                :loading="patientLoading"
                style="width: 100%"
                @change="handlePatientChange"
                :disabled="!!route.query.patientId || isEdit"
              >
                <el-option 
                  v-for="item in patientOptions" 
                  :key="item.id" 
                  :label="`${item.name} (${item.patientId})`"
                  :value="item.id" 
                >
                  <div class="patient-option">
                    <span>{{ item.name }}</span>
                    <span class="patient-id">{{ item.patientId }}</span>
                    <span class="patient-info">{{ item.gender }} {{ item.age }}岁</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="医疗记录" prop="medicalRecordId">
              <el-select 
                v-model="form.medicalRecordId" 
                filterable
                placeholder="请选择关联的医疗记录" 
                style="width: 100%"
                :disabled="!!route.query.medicalRecordId || isEdit"
              >
                <el-option 
                  v-for="item in medicalRecordOptions" 
                  :key="item.id" 
                  :label="`${item.visitId} (${formatDate(item.visitDate)})`"
                  :value="item.id" 
                >
                  <div class="record-option">
                    <span>就诊ID: {{ item.visitId }}</span>
                    <span class="record-info">{{ formatDate(item.visitDate) }}</span>
                    <el-tag size="small" type="info">{{ item.departmentName }}</el-tag>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="诊断" prop="diagnosis">
              <el-select 
                v-model="form.diagnosis" 
                placeholder="请选择诊断"
                style="width: 100%"
                :disabled="isEdit"
              >
                <el-option 
                  v-for="item in diagnosisOptions" 
                  :key="item.id" 
                  :label="item.name"
                  :value="item.name" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="开具科室" prop="departmentId">
              <el-select 
                v-model="form.departmentId" 
                placeholder="请选择科室" 
                filterable
                style="width: 100%"
                @change="handleDepartmentChange"
                :disabled="!!route.query.departmentId || isEdit"
              >
                <el-option 
                  v-for="item in departmentOptions" 
                  :key="item.id" 
                  :label="item.name" 
                  :value="item.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="开具医生" prop="doctorId">
              <el-select 
                v-model="form.doctorId" 
                placeholder="请选择医生" 
                filterable
                style="width: 100%"
                :disabled="!!route.query.doctorId || isEdit"
              >
                <el-option 
                  v-for="item in doctorOptions" 
                  :key="item.id" 
                  :label="`${item.name} (${item.title})`" 
                  :value="item.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-divider content-position="left">处方内容</el-divider>
        
        <el-form-item label="处方药品" prop="items">
          <el-table :data="form.items" style="width: 100%" border>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  size="small" 
                  circle
                  @click="removeItem(scope.$index)"
                  :disabled="isEdit && form.status !== '待审核'"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="药品名称" width="200">
              <template #default="scope">
                <el-select 
                  v-model="scope.row.drugId" 
                  filterable 
                  remote 
                  reserve-keyword
                  placeholder="请输入药品名称搜索" 
                  :remote-method="searchDrugs"
                  :loading="drugLoading"
                  style="width: 100%"
                  @change="(val) => handleDrugChange(val, scope.$index)"
                  :disabled="isEdit && form.status !== '待审核'"
                >
                  <el-option 
                    v-for="item in drugOptions" 
                    :key="item.id" 
                    :label="item.name"
                    :value="item.id" 
                  >
                    <div class="drug-option">
                      <span>{{ item.name }}</span>
                      <span class="drug-spec">{{ item.specification }}</span>
                    </div>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="药品规格" width="180">
              <template #default="scope">
                <el-input v-model="scope.row.specification" placeholder="规格" disabled></el-input>
              </template>
            </el-table-column>
            <el-table-column label="单位" width="80">
              <template #default="scope">
                <el-input v-model="scope.row.unit" placeholder="单位" disabled></el-input>
              </template>
            </el-table-column>
            <el-table-column label="用法" width="150">
              <template #default="scope">
                <el-select 
                  v-model="scope.row.usage" 
                  placeholder="用法" 
                  style="width: 100%"
                  :disabled="isEdit && form.status !== '待审核'"
                >
                  <el-option label="口服" value="口服" />
                  <el-option label="静脉注射" value="静脉注射" />
                  <el-option label="肌肉注射" value="肌肉注射" />
                  <el-option label="皮下注射" value="皮下注射" />
                  <el-option label="外用" value="外用" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="剂量" width="100">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.dosage" 
                  :min="0" 
                  :precision="2"
                  controls-position="right"
                  style="width: 100%"
                  :disabled="isEdit && form.status !== '待审核'"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="频次" width="120">
              <template #default="scope">
                <el-select 
                  v-model="scope.row.frequency" 
                  placeholder="频次" 
                  style="width: 100%"
                  :disabled="isEdit && form.status !== '待审核'"
                >
                  <el-option label="每日一次" value="每日一次" />
                  <el-option label="每日两次" value="每日两次" />
                  <el-option label="每日三次" value="每日三次" />
                  <el-option label="每周一次" value="每周一次" />
                  <el-option label="必要时使用" value="必要时使用" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="数量" width="100">
              <template #default="scope">
                <el-input-number 
                  v-model="scope.row.quantity" 
                  :min="1" 
                  :precision="0"
                  controls-position="right"
                  style="width: 100%"
                  @change="calculateItemAmount(scope.$index)"
                  :disabled="isEdit && form.status !== '待审核'"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="单价(元)" width="100">
              <template #default="scope">
                <el-input 
                  v-model="scope.row.unitPrice" 
                  placeholder="单价" 
                  disabled
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="金额(元)" width="100">
              <template #default="scope">
                <el-input 
                  v-model="scope.row.amount" 
                  placeholder="金额" 
                  disabled
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px; display: flex; justify-content: space-between;">
            <el-button 
              type="primary" 
              @click="addItem"
              :disabled="isEdit && form.status !== '待审核'"
            >
              添加药品
            </el-button>
            <div class="total-amount">
              <span>总金额：</span>
              <span class="amount">¥ {{ calculateTotalAmount() }}</span>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="处方说明" prop="instructions">
          <el-input 
            v-model="form.instructions" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入处方说明、注意事项等" 
            :disabled="isEdit && form.status !== '待审核'"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="submitForm"
            :disabled="isEdit && form.status !== '待审核'"
          >
            保存
          </el-button>
          <el-button @click="cancelForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { prescriptionAPI, patientAPI, departmentAPI, doctorAPI, medicalRecordAPI, drugAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'

// 路由相关
const route = useRoute()
const router = useRouter()
const prescriptionId = computed(() => route.params.id)
const isEdit = computed(() => !!prescriptionId.value)

// 表单引用
const formRef = ref(null)

// 表单数据
const form = reactive({
  prescriptionId: '',
  status: '待审核',
  patientId: route.query.patientId || '',
  medicalRecordId: route.query.medicalRecordId || '',
  diagnosis: '',
  departmentId: route.query.departmentId || '',
  doctorId: route.query.doctorId || '',
  items: [],
  instructions: '',
  totalAmount: 0
})

// 表单验证规则
const rules = {
  patientId: [{ required: true, message: '请选择患者', trigger: 'change' }],
  medicalRecordId: [{ required: true, message: '请选择医疗记录', trigger: 'change' }],
  departmentId: [{ required: true, message: '请选择科室', trigger: 'change' }],
  doctorId: [{ required: true, message: '请选择医生', trigger: 'change' }],
  items: [{ 
    type: 'array', 
    required: true, 
    message: '请至少添加一个药品', 
    trigger: 'change',
    validator: (rule, value) => value.length > 0
  }],
}

// 患者选项
const patientOptions = ref([])
const patientLoading = ref(false)

// 医疗记录选项
const medicalRecordOptions = ref([])

// 诊断选项
const diagnosisOptions = ref([])

// 科室选项
const departmentOptions = ref([])

// 医生选项
const doctorOptions = ref([])

// 药品选项
const drugOptions = ref([])
const drugLoading = ref(false)

// 获取处方详情
const getPrescriptionDetail = async () => {
  try {
    const res = await prescriptionAPI.getPrescription(prescriptionId.value)
    // 填充表单数据
    Object.keys(form).forEach(key => {
      if (key in res.data && res.data[key] !== null) {
        form[key] = res.data[key]
      }
    })
    
    // 获取相关患者信息
    if (res.data.patientInfo) {
      patientOptions.value = [res.data.patientInfo]
    }
    
    // 获取医疗记录选项
    if (res.data.patientId) {
      getPatientMedicalRecords(res.data.patientId)
    }
    
    // 获取诊断选项
    if (res.data.medicalRecordId) {
      getMedicalRecordDiagnosis(res.data.medicalRecordId)
    }
    
    // 预加载科室医生信息
    if (form.departmentId) {
      getDoctorsByDepartment(form.departmentId)
    }
    
  } catch (error) {
    console.error('获取处方详情失败', error)
    ElMessage.error('获取处方详情失败')
  }
}

// 添加药品项
const addItem = () => {
  form.items.push({
    drugId: '',
    drugName: '',
    specification: '',
    unit: '',
    usage: '口服',
    dosage: 1,
    frequency: '每日三次',
    quantity: 1,
    unitPrice: 0,
    amount: 0
  })
}

// 移除药品项
const removeItem = (index) => {
  form.items.splice(index, 1)
  calculateTotalAmount()
}

// 计算单项金额
const calculateItemAmount = (index) => {
  const item = form.items[index]
  if (item.quantity && item.unitPrice) {
    item.amount = (item.quantity * parseFloat(item.unitPrice)).toFixed(2)
  } else {
    item.amount = 0
  }
  calculateTotalAmount()
}

// 计算总金额
const calculateTotalAmount = () => {
  const total = form.items.reduce((sum, item) => {
    return sum + (parseFloat(item.amount) || 0)
  }, 0)
  form.totalAmount = total.toFixed(2)
  return form.totalAmount
}

// 搜索患者
const searchPatients = async (query) => {
  if (query.length < 2) return
  patientLoading.value = true
  try {
    const res = await patientAPI.getPatients({ 
      name: query,
      limit: 10
    })
    patientOptions.value = res.data.patients
  } catch (error) {
    console.error('搜索患者失败', error)
  } finally {
    patientLoading.value = false
  }
}

// 处理患者变化
const handlePatientChange = (patientId) => {
  // 清空相关字段
  form.medicalRecordId = ''
  form.diagnosis = ''
  
  // 获取患者的医疗记录
  getPatientMedicalRecords(patientId)
}

// 获取患者的医疗记录
const getPatientMedicalRecords = async (patientId) => {
  if (!patientId) return
  try {
    const res = await medicalRecordAPI.getMedicalRecords({
      patientId,
      status: ['已完成', '已签名'],
      limit: 20
    })
    medicalRecordOptions.value = res.data.records || []
  } catch (error) {
    console.error('获取患者医疗记录失败', error)
  }
}

// 监听医疗记录变化
watch(() => form.medicalRecordId, (newVal) => {
  if (newVal) {
    getMedicalRecordDiagnosis(newVal)
  } else {
    diagnosisOptions.value = []
    form.diagnosis = ''
  }
})

// 获取医疗记录的诊断
const getMedicalRecordDiagnosis = async (recordId) => {
  if (!recordId) return
  try {
    const res = await medicalRecordAPI.getMedicalRecord(recordId)
    if (res.data.diagnosis && res.data.diagnosis.length > 0) {
      diagnosisOptions.value = res.data.diagnosis
    }
  } catch (error) {
    console.error('获取医疗记录诊断失败', error)
  }
}

// 获取科室列表
const getDepartments = async () => {
  try {
    const res = await departmentAPI.getDepartments({ status: '启用' })
    departmentOptions.value = res.data.departments
  } catch (error) {
    console.error('获取科室列表失败', error)
  }
}

// 根据科室获取医生列表
const getDoctorsByDepartment = async (departmentId) => {
  if (!departmentId) return
  try {
    const res = await doctorAPI.getDoctors({ 
      departmentId,
      status: '在职'
    })
    doctorOptions.value = res.data.doctors
  } catch (error) {
    console.error('获取医生列表失败', error)
  }
}

// 处理科室变化
const handleDepartmentChange = (departmentId) => {
  form.doctorId = '' // 清空已选医生
  getDoctorsByDepartment(departmentId)
}

// 搜索药品
const searchDrugs = async (query) => {
  if (query.length < 2) return
  drugLoading.value = true
  try {
    const res = await drugAPI.getDrugs({ 
      name: query,
      limit: 10
    })
    drugOptions.value = res.data.drugs
  } catch (error) {
    console.error('搜索药品失败', error)
  } finally {
    drugLoading.value = false
  }
}

// 处理药品选择变化
const handleDrugChange = async (drugId, index) => {
  if (!drugId) return
  try {
    const res = await drugAPI.getDrug(drugId)
    // 更新表单中的药品信息
    form.items[index].drugName = res.data.name
    form.items[index].specification = res.data.specification
    form.items[index].unit = res.data.unit
    form.items[index].unitPrice = res.data.price
    
    // 计算金额
    calculateItemAmount(index)
  } catch (error) {
    console.error('获取药品详情失败', error)
  }
}

// 提交表单
const submitForm = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 确保所有药品项都有必要的信息
        const invalidItems = form.items.filter(item => !item.drugId || !item.quantity)
        if (invalidItems.length > 0) {
          ElMessage.warning('请完善所有药品信息')
          return
        }
        
        if (isEdit.value) {
          // 编辑模式
          await prescriptionAPI.updatePrescription(prescriptionId.value, form)
          ElMessage.success('处方更新成功')
        } else {
          // 新增模式
          await prescriptionAPI.createPrescription(form)
          ElMessage.success('处方创建成功')
        }
        // 返回列表页
        router.push('/prescriptions/list')
      } catch (error) {
        console.error('保存处方失败', error)
        ElMessage.error(error.message || '保存失败')
      }
    } else {
      ElMessage.warning('请完善表单信息')
      return false
    }
  })
}

// 取消表单
const cancelForm = () => {
  ElMessageBox.confirm('确认放弃当前编辑内容？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push('/prescriptions/list')
  }).catch(() => {})
}

// 页面加载时获取数据
onMounted(() => {
  // 获取基础数据
  getDepartments()
  
  // 如果有查询参数中的患者ID，获取患者信息
  if (form.patientId) {
    patientAPI.getPatient(form.patientId).then(res => {
      patientOptions.value = [res.data]
      // 获取患者的医疗记录
      getPatientMedicalRecords(form.patientId)
    }).catch(error => {
      console.error('获取患者信息失败', error)
    })
  }
  
  // 如果有查询参数中的医疗记录ID，获取诊断信息
  if (form.medicalRecordId) {
    getMedicalRecordDiagnosis(form.medicalRecordId)
  }
  
  // 如果有查询参数中的科室ID，获取医生列表
  if (form.departmentId) {
    getDoctorsByDepartment(form.departmentId)
  }
  
  // 编辑模式下获取详情
  if (isEdit.value) {
    getPrescriptionDetail()
  } else {
    // 新增模式，可以初始化一些默认值
    addItem()
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.patient-option, .drug-option, .record-option {
  display: flex;
  align-items: center;
}

.patient-id, .drug-spec, .record-info {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.patient-info {
  margin-left: auto;
  color: #909399;
  font-size: 12px;
}

.total-amount {
  font-size: 16px;
  margin-right: 20px;
  display: flex;
  align-items: center;
}

.total-amount .amount {
  color: #f56c6c;
  font-weight: bold;
  margin-left: 5px;
}
</style> 